package com.myMinistry.gui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;

import com.myMinistry.R;
import com.myMinistry.provider.MinistryDatabase;
import com.myMinistry.provider.MinistryService;

public class Preferences extends PreferenceActivity {
	private String[] mFileList;
    private File mPath = null;    
    private static final int DIALOG_LOAD_FILE = 1000;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        
        findPreference("backup").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        	public boolean onPreferenceClick(Preference preference) {
        		try {
        			File sd = Environment.getExternalStorageDirectory();
        			File data = Environment.getDataDirectory();
        			if (sd.canWrite()) {
        				Calendar now = Calendar.getInstance();
        				SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MMMM-dd hh-mm-ss-aaa");
        				String currentDBPath = "data/" + getPackageName() + "/databases/";
        				String backupDBPath = "Android/data/" + getPackageName() + ".backup/databases/";
        				File currentDB = new File(data, currentDBPath + MinistryDatabase.DATABASE_NAME);
        				File backupDBDirPath = new File(sd, backupDBPath);
        				File backupDB = new File(sd, backupDBPath + dateFormatter.format(now.getTime()).toString());
        				
        				if(!backupDBDirPath.exists())
        					backupDBDirPath.mkdirs();
        				
        				if (currentDB.exists()) {
        					@SuppressWarnings("resource")
							FileChannel src = new FileInputStream(currentDB).getChannel();
        					@SuppressWarnings("resource")
							FileChannel dst = new FileOutputStream(backupDB).getChannel();
        					dst.transferFrom(src, 0, src.size());
        					src.close();
        					dst.close();
        					Toast.makeText(getBaseContext(), R.string.exportText, Toast.LENGTH_SHORT).show();
        				}
        				else
        					Toast.makeText(getBaseContext(), R.string.exportTextError, Toast.LENGTH_SHORT).show();
        			}
        		} catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); }
        		return true;
        	}
        });
        
        findPreference("restore").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        	public boolean onPreferenceClick(Preference preference) {
        		loadFileList();
        		showDialog(DIALOG_LOAD_FILE);
        		return true;
        	}
        });
        
        findPreference("clearBackups").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        	public boolean onPreferenceClick(Preference preference) {
        		loadFileList();
        		// If the file list is not null and the list is larger than 1 we have files to delete. 
        		if(mFileList != null && mFileList.length > 1) {
        			try {
	        			// Save which record is the newest.
	        			File lastModifiedFile = new File(mPath,mFileList[0]);
	        			int recordOfLastModifiedFile = 0;
	        			// Loop over the files and compare the dates to get the most recently modified file.
	        			for(int record = 0; record < mFileList.length; record++) {
	        				File file = new File(mPath,mFileList[record]);
	        				if(lastModifiedFile.lastModified() < file.lastModified()) {
	        					// Save the most recently saved file.
	        					lastModifiedFile = new File(mPath,mFileList[record]);
	        					recordOfLastModifiedFile = record;
	        				}
	        			}
	        			// Loop over the files and start deleting the files if they aren't the saved file gotten above.
	        			for(int record = 0; record < mFileList.length; record++) {
	        				if(record != recordOfLastModifiedFile) {
		        				File file = new File(mPath,mFileList[record]);
		        				file.delete();
		        			}
	        			}
	        			Toast.makeText(getBaseContext(), R.string.toast_cleaned_backups, Toast.LENGTH_SHORT).show();
	    			}
        			catch (Exception e) {
        				Toast.makeText(getBaseContext(), R.string.toast_cleaned_backups_error, Toast.LENGTH_SHORT).show();
	    			}
        		}
        		else
        			Toast.makeText(getBaseContext(), R.string.toast_cleaned_backups_only_one, Toast.LENGTH_SHORT).show();
        		return true;
        	}
        });
        
        findPreference("faqs").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        	public boolean onPreferenceClick(Preference preference) {
        		String url = "http://www.myministryassistant.com/faqs";  
        		Intent i = new Intent(Intent.ACTION_VIEW);  
        		i.setData(Uri.parse(url));  
        		startActivity(i);
        		return true;
        	}
        });
        
        findPreference("donate").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        	public boolean onPreferenceClick(Preference preference) {
        		String url = "http://www.myministryassistant.com/donate";  
        		Intent i = new Intent(Intent.ACTION_VIEW);  
        		i.setData(Uri.parse(url));  
        		startActivity(i);
        		return true;
        	}
        });
        
        findPreference("feedback").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        	public boolean onPreferenceClick(Preference preference) {
        		Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        		emailIntent.setType("text/plain");
        		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "developer@myministryassistant.com");
        		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, R.string.pref_feedback_cat + " - " + R.string.app_name);
        		startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        		return true;
        	}
        });
        
        findPreference("checkForUpdate").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        	public boolean onPreferenceClick(Preference preference) {
        		String versionName = "0";
				try {
					PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
					versionName = pi.versionName;
				} catch (NameNotFoundException e) {}
        		String url = "http://www.myministryassistant.com/download/" + versionName;
        		Intent i = new Intent(Intent.ACTION_VIEW);  
        		i.setData(Uri.parse(url));
        		startActivity(i);
        		return true;
        	}
        });
    }
    
    private void loadFileList() {
    	mPath = new File(Environment.getExternalStorageDirectory() + "/Android/data/" + getPackageName() + ".backup/databases/");
    	if(mPath.exists()) {
    		FilenameFilter filter = new FilenameFilter() {
    			public boolean accept(File dir, String filename) {
    				File sel = new File(dir, filename);
    				return filename.contains("") || sel.isDirectory();
    			}
    		};
    		mFileList = mPath.list(filter);
    		Arrays.sort(mFileList);
    	}
    	else
    		mFileList = new String[0];
    }
    
    @Override
	protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
    	AlertDialog.Builder builder = new Builder(this);
    	
    	switch(id) {
    		case DIALOG_LOAD_FILE: {
    			builder.setTitle(R.string.chooseBackup);
    			if(mFileList == null) {
    				dialog = builder.create();
    				return dialog;
    			}
    			builder.setItems(mFileList, new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int which) {
    					try {
    						MinistryService database = new MinistryService(getApplicationContext());
    						if(database.importDatabase(Environment.getExternalStorageDirectory() + "/Android/data/" + getPackageName() + ".backup/databases/" + mFileList[which].toString(), getPackageName()))
    							Toast.makeText(getBaseContext(), R.string.importText, Toast.LENGTH_SHORT).show();
    						else
    							Toast.makeText(getBaseContext(), R.string.importTextError, Toast.LENGTH_SHORT).show();
    					} catch (Exception e) { /* Nothing */ }
    				}
    			});
    			break;
    		}
    	}
    	dialog = builder.show();
    	return dialog;
    }
}